package com.yl.nettylearning.netty.day03;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

/**
 * @author yangl
 * 1、SimpleChannelInboundHandler是 ChannelInboundHandlerAdapter 的子类
 * 2、HttpObject 客户端和服务器端通讯的数据，被封装成HttpObject
 */
public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    /**
     * 读取客户端数据
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        //判断msg是不是httprequest请求
        if (msg instanceof HttpRequest){
            System.out.println("msg 类型：" + msg.getClass());
            System.out.println("客户端地址：" + ctx.channel().remoteAddress());

            //通过uri过滤指定的资源 每个浏览器都有一个独立的pipeline和channel
            HttpRequest httpRequest = (HttpRequest) msg;
            URI uri = new URI(httpRequest.uri());
            System.out.println(uri.getPath());
            if("/favicon.ico".equals(uri.getPath())){
                return;
            }

            //回复信息给浏览器[http协议]
            ByteBuf content = Unpooled.copiedBuffer("hello , 我是服务器端", CharsetUtil.UTF_8);
            //构造一个http响应，即httpresponse
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
            //设置返回头响应格式content-type
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            //设置返回头响应长度 content-length
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
            //将构建好的response返回
            ctx.writeAndFlush(response);

        }
    }
}
